package com.easy.project.base.validate.validator;

import com.easy.project.base.constant.IBaseEnumParam;
import com.easy.project.base.validate.EnumValidate;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Objects;

/**
 * 枚举验证器
 * @author wxz
 */
public class EnumValidator implements ConstraintValidator<EnumValidate,Object> {

    private String[] enums;

    private Class<? extends IBaseEnumParam<?>> baseEnum;

    @Override
    public boolean isValid(Object val, ConstraintValidatorContext constraintValidatorContext) {
        // 优先执行基础的枚举判断
        if (Objects.nonNull(baseEnum)){
            IBaseEnumParam<?>[] enumConstants = baseEnum.getEnumConstants();
            for (IBaseEnumParam<?> baseEnumParam : enumConstants){
                if (Objects.equals(String.valueOf(baseEnumParam.getCode()),String.valueOf(val))){
                    return true;
                }
            }
            return false;
        }
        if (this.enums == null || this.enums.length == 0){
            return true;
        }
        for (String enumVal : enums){
            if (Objects.equals(enumVal,String.valueOf(val))){
                return true;
            }
        }
        return false;
    }

    @Override
    public void initialize(EnumValidate constraintAnnotation) {

        this.enums = constraintAnnotation.enums();
        this.baseEnum = constraintAnnotation.baseEnum();
    }

}
